package com.anjie.powerproject.controller;

import com.anjie.powerproject.entity.Electricity;
import com.anjie.powerproject.entity.GraphInfo;
import com.anjie.powerproject.service.ElectricityPriceService;
import com.anjie.powerproject.service.GraphInfoService;
import com.anjie.powerproject.strategy.BaseWorkStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("electricity")
public class ElectricityPriceController {
    @Autowired
    private ElectricityPriceService electricityPriceService;

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private BaseWorkStrategy baseWorkStrategy;

    /**
     * 获取json格式的所有图谱信息，用于电价界面下拉框选择图谱
     * @return
     */
    @GetMapping("/viewGraphInfo")
    @ResponseBody
    public Map viewGraphInfo(@RequestParam(value = "graphId", required = false) Integer graphId) throws ParseException {
        Map map = new HashMap();
        List<GraphInfo> allGraphInfo = graphInfoService.getAllGraphInfo();
//        Date date = new Date();
        if (graphId == null) {
            graphId = baseWorkStrategy.getGraphId();
        }
        map.put("allGraphInfo",allGraphInfo);
        map.put("graphId",graphId);
        return map;
    }

    /**
     * 根据选择的图谱返回相应的电价，0-谷，1-平，2-峰
     * @return
     */
    @GetMapping("/viewPriceByGraphId/{graph_id}")
    @ResponseBody
    public Map<String, Object> getPriceByGraphId(@PathVariable("graph_id") Integer graph_id){
        Map<String, Object> map = new HashMap<>();
        // 简化逻辑，把大部分业务逻辑放在sql层
        List<Electricity> electricities = electricityPriceService.getElectricityListByGraphId(graph_id);
        // 没结果就表示无电价信息，理论上不可能出现选择的图谱不存在的情况，因为下拉框中都是系统中存在的图谱
        if (electricities != null && electricities.size() > 0) {
            StringBuilder high = new StringBuilder();
            StringBuilder low = new StringBuilder();
            StringBuilder mid = new StringBuilder();
            for(Electricity price:electricities){
                if(price.getEleType() == 0){
                    low.append(price.getStartTime()+"~"+price.getEndTime()+" ");
                }else if(price.getEleType() == 2){
                    high.append(price.getStartTime()+"~"+price.getEndTime()+" ");
                }else{
                    mid.append(price.getStartTime()+"~"+price.getEndTime()+" ");
                }
            }
            map.put("prices",electricities);
            map.put("high",high);
            map.put("mid",mid);
            map.put("low",low);
            return map;
        }
        map.put("msg","当前选择的图谱暂无电价信息。");
        return map;
    }

    /**
     * 根据选择的图谱跳转至电价修改页面
     * @param
     * @return
     */
    @GetMapping("/editElePrice/{graph_id}")
    public String editElectricityPrice(@PathVariable("graph_id") Integer graph_id,Model model){
        List<Electricity> electricities = electricityPriceService.getElectricityListByGraphId(graph_id);
        model.addAttribute("prices",electricities);
        model.addAttribute("graphId",graph_id);
        return "elePriceEdit";
    }

    /**
     * 修改电价
     * @param request
     * @return
     */
    @PostMapping("/updateElePrice/{graphId}")
    public String updateElectricityPrice(@PathVariable("graphId")Integer graphId,HttpServletRequest request, Model model){
        //已经存在的需要修改的
        String[] startTimeList = request.getParameterValues("startTimeList");
        String[] endTimeList = request.getParameterValues("endTimeList");
        String[] priceList = request.getParameterValues("priceList");
        String[] idList = request.getParameterValues("idList");
        if(priceList != null){
            for(int i = 0;i < priceList.length;i++){
                if(priceList[i] == ""){
                    priceList[i] = "0";
                }
                electricityPriceService.updateElePrice(startTimeList[i],endTimeList[i],Double.parseDouble(priceList[i]),Integer.parseInt(idList[i]));
            }
        }
        //新增的时间段及电价
        String[] startTimeAddList = request.getParameterValues("startTimeAddList");
        String[] endTimeAddList = request.getParameterValues("endTimeAddList");
        String[] priceAddList = request.getParameterValues("priceAddList");
        List<Electricity> electricities = new ArrayList<>();
        if(priceAddList != null){
            for (int j=0;j<priceAddList.length;j++){
                if(priceAddList[j] == ""){
                    priceAddList[j] = "0";
                }
                Electricity electricity = new Electricity(startTimeAddList[j],endTimeAddList[j],Double.parseDouble(priceAddList[j]),graphId,0);
                electricities.add(electricity);
            }
            electricityPriceService.saveElePrice(electricities);
        }
        //删除指定时间段
        String list = request.getParameter("idDeleteList");
        System.out.println("测试：" + list);
        if(list != null){
            String[] idDeleteList = list.split(",");
            for (String item: idDeleteList) {
                electricityPriceService.deleteElePrice(Integer.parseInt(item));
            }
        }

        electricityPriceService.autoUpdateEleType(graphId);

        model.addAttribute("graphId", graphId);
        return "elePrice";
    }

    /**
     * 根据id删除某个时间段的数据
     * @param eleId
     * @return
     */
    @RequestMapping("/deleteElePriceOvertime/{eleId}")
    public String deleteElectricityPriceOvertime(@PathVariable("eleId") Integer eleId){
        Electricity electricity = electricityPriceService.findElePriceById(eleId);
        electricityPriceService.deleteElePrice(eleId);
        return "redirect:/electricity/editElePrice/"+electricity.getGraphId();
    }

    @RequestMapping("/back/{graphId}")
    public String backToPrev(@PathVariable("graphId") Integer graphId, Model model) {
        model.addAttribute("graphId", graphId);
        return "elePrice";
    }
}
